<script setup>
// import { detail, dict } from "@/services/order.js";
// import html2canvas from "html2canvas";
import { nextTick, ref, watch } from "vue";
import {
  onLoad,
  onShow,
  onShareAppMessage,
  onShareTimeline,
} from "@dcloudio/uni-app";
import canvashbtwo from "@/pages/goods/components/canvashbtwo.vue";
import { userloginStore } from "@/stores/islogin.js";

import { productdetails, recommend, productqrcode } from "@/services/goods.js";
import { relationstate, relationcollect } from "@/services/user.js";
import { formatPrice } from "@/utils/formatPrice";
import { useaddressStore } from "@/stores/address";

const dateobj = useaddressStore();
const capture = ref(null);
const urlImage = ref("");

//海报参数
//画布组件参数
/**
 * 海报背景图片
 * url--图片地址
 * l---距离画布左边
 * t---距离画布顶部
 * w---图片宽
 * h---图片高
 * */
const bgimg = ref({
  url: "https://lmt-app-cloud.yibaitao.com/20240528/ca0c736d-e1c7-3174-90d4-6d5c02213105.png",
  w: 710,
  h: 710,
  l: 20,
  t: 120,
});

/**
 * 二维码图片
 * url--图片地址
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * w---number---图片宽
 * h---number---图片高
 * */
const codeimg = ref({
  url: "https://lmt-app-cloud.yibaitao.com/20240604/86ed26a6-61e3-4ef3-60dd-95099af50a85.png",
  w: 186,
  h: 186,
  l: 544,
  t: 840,
});
/**
 * logon图片
 * url--string--图片地址
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * w---number---图片宽
 * h---number---图片高
 * */
const logo = ref({
  url: "https://m-cloud.yibaitao.com/fe/022ce0547f4772707246c17779f7fa.png",
  l: 20,
  t: 30,
  w: 60,
  h: 60,
});
/**
 *海报标题
 * name--string --标题 名称
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * size---number--字体大小
 * color---#cccccc---字体颜色
 * */
const titlename = ref({
  name: "我是标题哦",
  l: 20,
  t: 880,
  size: 34,
  color: "black",
});

/**
 *金额数量
 * name--string --标题 名称
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * size---number--字体大小
 * color---#cccccc---字体颜色
 * */
const money = ref({
  name: "10000",
  l: 60,
  t: 1004,
  size: 54,
  color: "#B63434",
});
/**
 *备用说明
 * name--string --标题 名称
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * size---number--字体大小
 * color---#cccccc---字体颜色
 * */
const logoname = ref({
  name: "膳友会",
  l: 100,
  t: 75,
  size: 34,
  color: "black",
});
/**
 *备用说明
 * name--string --标题 名称
 * l---number---距离画布左边
 * t---number---距离画布顶部
 * size---number--字体大小
 * color---#cccccc---字体颜色
 * */
const btneme = ref({
  name: "默认",
  l: 20,
  t: 955,
  size: 30,
  color: "#666666",
});

const showshare = ref(false);
const cloeshbfun = () => {
  showshare.value = false;
};
// setTimeout(() => {
//   showshare.value = true;
// }, 1000);

//轮播图
const userlogin = userloginStore();
const indicatorDots = ref(false);
const autoplay = ref(true);
const interval = ref(5000);
const duration = ref(500);
const ablum = ref(null);
const projectdet = ref(null);
const store = ref({});
const order = ref(null);
const dictorderpay = ref({});
const urlnum = ref(0);
const relationstateselect = ref(0);
const goodsid = ref("");

const aaa2 = ref(null);

// const generateImage = async () => {
//   nextTick(() => {
//     // console.log(capture.value);

//     console.log(capture.value.textContent, aaa2.value.text);
//   });
//   try {
//     const element = capture.value;
//     console.log(element);
//     const canvas = await html2canvas(element, {
//       useCORS: true, // 允许跨域图片
//       allowTaint: false, // 不允许污染
//     });
//     const dataURL = canvas.toDataURL("image/png");
//     console.log(dataURL); // 这里可以将 dataURL 保存或显示
//     urlImage.value = dataURL;
//   } catch (error) {
//     console.error("生成图片失败", error);
//   }
// };

onLoad((e) => {
  let codes = "";
  console.log(e);

  // #ifdef MP-WEIXIN
  if (e.scene) {
    codes = getUrlParams(decodeURIComponent(e.scene));
    goodsid.value = codes.id;
  } else {
    goodsid.value = e.id;
  }

  // #endif
  // #ifndef MP-WEIXIN
  goodsid.value = e.id;
  // #endif
  getprojectdet(e.id);
});

onShow(() => {
  if (dateobj.address) {
    dateobj.setaddress("");
  }
  relationstatefun(goodsid.value);
  // getrecommendfun();
  watch(
    userlogin,
    (newVal, oldVal) => {
      if (newVal.islogin) {
        relationstatefun(goodsid.value);
        // getrecommendfun();
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );
});

// #ifdef MP-WEIXIN

onShareAppMessage(() => {
  return {
    title: dictorderpay.value.store_name,
    path: "/pages/goods/details/index",
    imageUrl: dictorderpay.value.slider_image[0],
  };
});

// 朋友圈分享
onShareTimeline(() => {
  return {
    title: dictorderpay.value.store_name,
    path: "/pages/goods/details/index",
    imageUr: dictorderpay.value.slider_image[0],
  };
});
// #endif

async function getprojectdet(id) {
  store.value.ablum = [];

  store.value.ablum = [];

  try {
    const resdict = await productdetails({ id: id });
    dictorderpay.value = resdict.data;
    urlnum.value = resdict.data.slider_image.length;
    if (resdict.code == 200) {
      // codeimg.value.url = resdict.data.web_qrcode;
      bgimg.value.url = resdict.data.slider_image[0];
      titlename.value.name = resdict.data.store_name;
    }
  } catch (error) {
    //返回上一页
    uni.navigateBack({
      delta: 1, // 返回的页面数
    });
    setTimeout(() => {
      uni.showToast({
        title: error.info,
        icon: "none",
      });
    }, 100);
    return;
  }

  // const res = await detail({
  //   id: id,
  // });

  // store.value = res.result.store;
  // projectdet.value = res.result.items;
  // order.value = res.result.order;
}

async function relationstatefun(id) {
  if (!userlogin.islogin) {
    return;
  }
  try {
    const resdict = await relationstate({ product_id: goodsid.value });
    relationstateselect.value = resdict.data.state;
    if (resdict.code == 200) {
    }
  } catch (e) {}
}

const relationcollectfun = async (id) => {
  try {
    const resdict = await relationcollect({ product_id: id });
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }

  relationstatefun(id);
};

const recommendobj = ref([]);
async function getrecommendfun() {
  if (!userlogin.islogin) {
    return;
  }
  const res = await recommend({ product_id: goodsid.value });
  recommendobj.value = res.data;
}
function discfun(index) {
  var name = "";
  dictorderpay.value.forEach((item, index) => {
    if (item.value === index) {
      name = item.label;
    }
  });
  return name;
}

// const collapse = ref(null)
// nextTick(() => {
// 	collapse.value.resize()
// })
// const collapsefun = () => {
// }
const payshow = ref(false);
const closepopup = () => {
  payshow.value = false;
};
const payfun = () => {
  uni.showToast({
    title: "暂不支持在线下单，请到店铺购买",
    icon: "none",
  });
  return;

  if (dictorderpay.value.is_forsale == 0) {
    uni.showToast({
      title: "商品已售罄,请选择其他商品",
      icon: "none",
    });
    return;
  }
  uni.navigateTo({
    url: `/pages/goods/order_confirm/index?id=${dictorderpay.value.product_id}`,
  });

  // payshow.value = true;
};

const open = (e) => {};

// 定义 close 方法
const close = (e) => {};

// 定义 change 方法
const change = (e) => {};
const current = ref(0);

const cypefun = (string) => {
  uni.setClipboardData({
    data: string,
    success: function () {
      uni.showToast({
        title: "已复制到粘贴板",
        icon: "none",
      });
    },
  });
};

const deletefun = () => {
  uni.showToast({
    title: "暂时无法删除",
    icon: "none",
  });
};
const changefun = (event) => {
  current.value = event.detail.current;
};
const sharefun = async () => {
  const res = await productqrcode({ product_id: goodsid.value });
  if (res.code == 200) {
    console.log(res.data);
    codeimg.value.url = res.data.qrcode;
    showshare.value = true;
  }
};
const godetails = (id) => {
  getprojectdet(id);
  // uni.navigateTo({
  //   url: `/pages/goods/details/index?id=${id}`,
  // });
};
</script>

<template>
  <view class="projectdet">
    <view class="projectdet-top">
      <view class="uni-margin-wrap">
        <swiper
          class="swiper"
          circular
          :current="current"
          :indicator-dots="indicatorDots"
          :autoplay="autoplay"
          :interval="interval"
          :duration="duration"
          @change="changefun"
        >
          <swiper-item
            v-for="(item, index) in dictorderpay && dictorderpay.slider_image"
            :key="index"
          >
            <!--  -->
            <view class="swiper-item">
              <image :src="item" mode="aspectFill"></image>
            </view>
          </swiper-item>
        </swiper>
        <view class="swiper-dot">
          <text>{{ current + 1 }}</text
          >/<text>{{ urlnum }}</text>
        </view>
        <view class="share" @click="sharefun">
          <up-icon name="share" color="#ffffff" size="24rpx"></up-icon>

          <text>分享</text>
        </view>
      </view>
    </view>
    <view class="projectdet-content">
      <view class="store">
        <view class="store-title">{{
          dictorderpay && dictorderpay.store_name
        }}</view>
        <view class="store-price">
          <view class="store-price-left">
            <!-- <view class="store-last-child"
              >售价：<text class="old-num"
                >￥{{ formatPrice(dictorderpay && dictorderpay.price) }}</text
              ></view
            > -->
            <view
              >售价：<text class="text-dw">¥</text
              ><text class="num">{{
                formatPrice(
                  dictorderpay && dictorderpay.price ? dictorderpay.price : 0
                )
              }}</text></view
            >
          </view>
          <!-- <view class="store-price-right">
            <text>购买可升级为店主</text>
          </view> -->
        </view>
        <view class="store-dec">
          <text>
            {{ dictorderpay.refund_switch == 1 ? "可退换货" : "不可退换" }}
          </text>
          <text>
            {{ dictorderpay.is_package == 0 ? "普通商品" : "礼包商品" }}</text
          >
          <!-- <text>赠送店主身份</text> -->
        </view>
      </view>
    </view>

    <view class="shop-det">
      <view class="shop-det-title">
        <text class="hengx"></text>
        <text>商品介绍</text>
        <text class="hengx"></text>
      </view>
      <div class="shop-det-content">
        <up-parse :content="dictorderpay && dictorderpay.content"></up-parse>
      </div>
    </view>

    <view class="user-shop" v-if="recommendobj.length > 0">
      <view class="user-shop-item"><text>推荐商品</text> </view>

      <view class="shop-list">
        <view
          class="shop-list-item"
          v-for="(item, index) in recommendobj"
          :key="index"
          @click="godetails(item.product_id)"
        >
          <view class="shop-list-image">
            <image :src="item.image" mode="aspectFill" />
          </view>

          <view class="shop-list-name"> {{ item.store_name }} </view>
          <view class="shop-list-price">
            <text>¥</text>
            {{ formatPrice(item.vip_price) }}
          </view>
        </view>
      </view>
    </view>
  </view>

  <!-- <up-popup
    :show="payshow"
    mode="center"
    round="10"
    @close="close"
    @open="open"
  >
    <view class="popup-content">
      <view class="popup-content-title">温馨提示</view>
      <view class="popup-content-dec"
        >购买此商品，您需要签订《明松旺店主认购合同》</view
      >
      <view class="popup-content-bt">
        <u-button
          class="popup-content-qx"
          text="取消"
          @click="closepopup"
        ></u-button>
        <u-button class="popup-content-cl" text="查看合同"></u-button>
      </view>
    </view>
  </up-popup> -->
  <up-popup
    :show="payshow"
    mode="center"
    round="10"
    @close="close"
    @open="open"
  >
    <view class="popup-content">
      <view class="popup-content-title">温馨提示</view>
      <view class="popup-content-dec"
        >购买此商品，您需要签订《膳友会店主认购合同》</view
      >
      <view class="popup-content-bt">
        <u-button
          class="popup-content-qx"
          text="取消"
          @click="closepopup"
        ></u-button>
        <u-button class="popup-content-cl" text="去下单"></u-button>
      </view>
    </view>
  </up-popup>

  <view class="foodr-k">
    <view class="foodr-k-in">
      <view class="foodr-left">
        <navigator
          url="/pages/index/index"
          open-type="switchTab"
          hover-class="navigator-hover"
        >
          <view class="foodr-left-item">
            <image src="@/pages/goods/static/home.png" mode="scaleToFill" />
            <view ref="aaa2">首页</view>
          </view>
        </navigator>

        <view
          class="foodr-left-item"
          @click="relationcollectfun(dictorderpay.product_id)"
        >
          <image
            src="@/pages/goods/static/home_start.png"
            mode="scaleToFill"
            v-if="relationstateselect == 0"
          />
          <image
            src="@/pages/goods/static/home_start-select.png"
            mode="scaleToFill"
            v-else
          />

          <view v-if="relationstateselect == 0">收藏</view>
          <view class="foodr-left-item-color" v-else>已收藏</view>
        </view>

        <!-- <view class="foodr-left-item">
          <image
            src="@/pages/goods/static/home_start-select.png"
            mode="scaleToFill"
          />
          <view>收藏</view>
        </view> -->
      </view>

      <view class="foodr-right">
        <view class="recharge" @click="payfun">
          {{ dictorderpay.is_forsale == 0 ? "已售罄" : "立即购买" }}
        </view>
      </view>
    </view>
  </view>
  <canvashbtwo
    v-if="showshare"
    @cloes-Event="cloeshbfun"
    :bgimg="bgimg"
    :codeimg="codeimg"
    :titlename="titlename"
    :logoname="logoname"
    :logo="logo"
    :btneme="btneme"
    :showbt="false"
    :cw="750"
    :ch="1050"
  ></canvashbtwo>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
